package com.example.clusterclientconsumer;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * <p>
 * </p>
 *
 * @author Zero
 * @since 2019/3/5
 */
@RestController
public class ExampleController {

    @Value("${spring.application.name}")
    private String appname;

    @Value("${server.port}")
    private Integer port;

    @Autowired
    private ExampleService exampleService;

    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public String hello(@RequestParam(value = "name") String name) {
        try {
            return exampleService.hello(name);
        } catch (Exception e) {
            e.printStackTrace();
            return "接口调用异常：" + e.getMessage();
        }
    }

    @RequestMapping(value = "/test", method = RequestMethod.GET)
    public Map<String, Object> test(@RequestParam(value = "name") String name) {
        try {
            Map<String, Object> map = exampleService.test(name);
            map.put("consumer-name", appname);
            map.put("consumer-port", port);
            map.put("consumer-param", name);
            map.put("consumer-session-id", getSession().getId());
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static HttpSession getSession() {
        return getRequest().getSession();
    }

    public static HttpServletRequest getRequest() {
        ServletRequestAttributes attrs =(ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return attrs.getRequest();
    }

}
